// 立即执行函数，避免全局变量污染
(() => {
    // 全局配置对象
    const config = window.config || {};
    
    // 更新车牌号显示
    function updateLicensePlate() {
        const licensePlateElement = document.getElementById('licensePlate');
        if (licensePlateElement && config.carInfo && config.carInfo.licensePlate) {
            licensePlateElement.textContent = config.carInfo.licensePlate;
        }
    }
    
    // 初始化应用
    function initApp() {
        // 更新车牌号显示
        updateLicensePlate();
    
        // DOM元素引用
    const elements = {
        notifyBtn: document.getElementById('notifyBtn'),
        messageInput: document.getElementById('messageInput'),
        messageTemplate: document.getElementById('messageTemplate'),
        callSlider: document.getElementById('callSlider'),
        callHandle: document.getElementById('callHandle'),
        callProgress: document.getElementById('callProgress'),
        historyList: document.getElementById('historyList'),
        historyCount: document.getElementById('historyCount'),
        clearHistoryBtn: document.getElementById('clearHistoryBtn'),
        toastContainer: document.getElementById('toastContainer'),
        themeToggleBtn: document.getElementById('themeToggleBtn'),
        urgencyBtns: document.querySelectorAll('.urgency-btn')
    };

        // 状态管理
        const state = {
            lastNotifyTime: 0,
            isDragging: false,
            startX: 0,
            currentX: 0,
            maxProgress: 0,
            notificationHistory: JSON.parse(localStorage.getItem('notificationHistory') || '[]'),
            currentUrgency: 'urgent',
            hasCreatedCallRecord: false // 防止一次滑动创建多条记录
        };

        // 用户交互状态标志
        let hasUserInteracted = false;
        
        // 检测用户第一次交互
        function detectUserInteraction() {
            if (!hasUserInteracted) {
                hasUserInteracted = true;
                document.removeEventListener('click', detectUserInteraction);
                document.removeEventListener('touchstart', detectUserInteraction);
            }
        }
        
        // 添加事件监听器以检测用户交互
        document.addEventListener('click', detectUserInteraction);
        document.addEventListener('touchstart', detectUserInteraction);
        
        // 触觉反馈功能 - 仅在用户交互后执行
        const hapticFeedback = {
            light: () => hasUserInteracted && navigator.vibrate?.(10),
            medium: () => hasUserInteracted && navigator.vibrate?.(30),
            heavy: () => hasUserInteracted && navigator.vibrate?.([50, 50, 50]),
            success: () => hasUserInteracted && navigator.vibrate?.([50, 30, 50, 30, 50])
        };

        // 主题设置功能
        function setTheme(theme) {
            document.body.className = theme;
            elements.themeToggleBtn.textContent = theme === 'light' ? '☀️' : '🌙';
            elements.themeToggleBtn.classList.add('active');
            localStorage.setItem('theme', theme);
            hapticFeedback.light();
        }
        
        // 切换主题功能
        function toggleTheme() {
            const currentTheme = document.body.className || 'light';
            const newTheme = currentTheme === 'light' ? 'dark' : 'light';
            setTheme(newTheme);
        }

        // Toast提示功能
        function showToast(message, type = 'loading') {
            const toastIcon = elements.toastContainer.querySelector('.toast-icon');
            const toastMessage = elements.toastContainer.querySelector('.toast-message');
            
            toastMessage.textContent = message;
            toastIcon.innerHTML = `<div class="toast-${type}"></div>`;
            elements.toastContainer.classList.add('show');
            
            if (type === 'error') hapticFeedback.heavy();
            if (type === 'success') hapticFeedback.medium();

            return new Promise(resolve => {
                if (type !== 'loading') {
                    setTimeout(() => {
                        elements.toastContainer.classList.remove('show');
                        setTimeout(resolve, 300);
                    }, 2000);
                } else {
                    resolve();
                }
            });
        }

        // 更新历史记录显示
        function updateHistoryDisplay() {
            // 根据历史记录数量更新显示
            if (state.notificationHistory.length === 0) {
                elements.historyList.style.display = 'none';
                elements.historyCount.style.display = 'none';
                elements.clearHistoryBtn.style.display = 'none';
            } else {
                elements.historyList.style.display = 'block';
                elements.historyCount.style.display = 'block';
                elements.clearHistoryBtn.style.display = 'inline-block';
                elements.historyCount.textContent = `${state.notificationHistory.length}条记录`;
                elements.historyList.innerHTML = state.notificationHistory.map(notification => {
                    const urgencyClass = notification.urgency ? 
                        `history-urgency-${notification.urgency}` : 
                        'history-urgency-urgent';
                    const urgencyText = notification.urgency ? 
                        (notification.urgency === 'urgent' ? '紧急' : '非常紧急') : 
                        '紧急';
                    
                    // 判断记录类型，添加相应的图标和样式
                    const recordType = notification.type || 'sms';
                    const recordIcon = recordType === 'call' ? '📞' : '📱';
                    const recordTypeClass = `history-type-${recordType}`;
                    
                    return `
                    <div class="history-item ${recordTypeClass}">
                        <div class="history-header">
                            <span class="history-message">
                                <span class="history-icon">${recordIcon}</span>
                                ${notification.message}
                            </span>
                            <span class="history-urgency ${urgencyClass}">${urgencyText}</span>
                        </div>
                        <div class="history-time">
                            ${new Date(notification.timestamp).toLocaleString()}
                        </div>
                    </div>
                `;}).join('');
            }
        }

        // 设置紧急程度
        function setUrgency(urgency) {
            state.currentUrgency = urgency;
            
            // 更新按钮选中状态
            elements.urgencyBtns.forEach(btn => {
                btn.classList.toggle('active', btn.dataset.urgency === urgency);
            });
            
            // 根据紧急程度切换显示状态
            const isUrgent = urgency === 'urgent';
            const isVeryUrgent = urgency === 'very-urgent';
            elements.notifyBtn.style.display = isUrgent ? 'block' : 'none';
            elements.callSlider.style.display = isVeryUrgent ? 'block' : 'none';
            
            hapticFeedback.light();
        }

        // 脏话检测函数
        function containsProfanity(text) {
            // 从配置中获取脏话列表
            const profanityList = config.profanityList || [];
            
            const lowerText = text.toLowerCase();
            return profanityList.some(profanity => lowerText.includes(profanity.toLowerCase()));
        }

        // 通知车主功能
        async function notifyOwner() {
            const now = Date.now();
            const cooldown = config.notification.cooldown || 120000;
            
            if (now - state.lastNotifyTime < cooldown) {
                const remaining = Math.ceil((cooldown - (now - state.lastNotifyTime)) / 1000);
                await showToast(
                    `请等待 ${Math.floor(remaining / 60)}分${remaining % 60}秒后再次通知`,
                    'error'
                );
                return;
            }

            const message = elements.messageInput.value.trim() || config.notification.defaultMessage;
            const urgency = state.currentUrgency;
            
            // 检查自定义消息是否包含脏话（如果用户输入了自定义消息）
            if (elements.messageInput.value.trim() && containsProfanity(message)) {
                await showToast('您的消息包含不适当内容，请修改后重试', 'error');
                hapticFeedback.heavy();
                return;
            }
            
            hapticFeedback.medium();
            await showToast('正在准备短信...', 'loading');
            
            try {
                // 准备短信内容 - 移除前缀和后缀
                const smsContent = encodeURIComponent(message);
                
                // 创建通知记录
                const notification = {
                    id: Date.now().toString(),
                    message,
                    urgency,
                    type: 'sms',
                    timestamp: now
                };

                state.notificationHistory = [notification, ...state.notificationHistory].slice(0, 10);
                localStorage.setItem('notificationHistory', JSON.stringify(state.notificationHistory));
                updateHistoryDisplay();

                // 触发短信应用
                hapticFeedback.success();
                await showToast('正在打开短信应用...', 'success');
                state.lastNotifyTime = now;
                
                // 清空输入
                elements.messageInput.value = '';
                elements.messageTemplate.value = '';
                
                // 延迟打开短信应用，确保Toast可以正常显示
                setTimeout(() => {
                    window.location.href = `sms:${config.phone}?body=${smsContent}`;
                }, 1000);
            } catch (error) {
                console.error('处理失败:', error);
                hapticFeedback.heavy();
                await showToast('处理失败，请重试', 'error');
            }
        }

        // 滑块更新功能
        function updateSlider(clientX) {
            const rect = elements.callSlider.getBoundingClientRect();
            const maxX = rect.width - elements.callHandle.offsetWidth;
            state.currentX = Math.max(0, Math.min(maxX, clientX - rect.left - elements.callHandle.offsetWidth / 2));
            
            const progress = (state.currentX / maxX) * 100;
            
            if (progress > state.maxProgress) {
                state.maxProgress = progress;
                if (progress > 25 && progress < 90) {
                    hapticFeedback.light();
                }
            }
            
            elements.callHandle.style.transform = `translateX(${state.currentX}px)`;
            elements.callProgress.style.width = `${progress}%`;

            if (progress > 90 && !state.hasCreatedCallRecord) {
                state.hasCreatedCallRecord = true; // 标记已创建记录，防止重复创建
                hapticFeedback.success();
                
                // 创建通话记录
                const callRecord = {
                    id: Date.now().toString(),
                    message: '拨打电话通知',
                    urgency: 'very-urgent',
                    type: 'call',
                    timestamp: Date.now()
                };
                
                // 添加到历史记录并更新
                state.notificationHistory = [callRecord, ...state.notificationHistory].slice(0, 10);
                localStorage.setItem('notificationHistory', JSON.stringify(state.notificationHistory));
                updateHistoryDisplay();
                
                // 拨打电话
                window.location.href = `tel:${config.phone}`;
                setTimeout(resetSlider, 300);
            }
        }

        // 重置滑块状态
        function resetSlider() {
            elements.callHandle.style.transform = 'translateX(0)';
            elements.callProgress.style.width = '0';
            state.currentX = 0;
            state.isDragging = false;
            state.maxProgress = 0;
            state.hasCreatedCallRecord = false; // 重置通话记录创建标志
            hapticFeedback.medium();
        }

        // 结束拖动处理
        function endDrag() {
            if (!state.isDragging) return;
            state.isDragging = false;
            elements.callHandle.style.transition = 'transform 0.3s';
            elements.callProgress.style.transition = 'width 0.3s';
            resetSlider();
        }

        // 清理历史记录函数（自动清理1天前的记录）
            function cleanupHistory() {
                const now = Date.now();
                const oneDayAgo = now - 86400000; // 1天前的时间戳
                
                // 过滤出1天内的记录
                const filteredHistory = state.notificationHistory.filter(item => item.timestamp >= oneDayAgo);
                
                // 如果有记录被清理了，更新状态并保存
                if (filteredHistory.length !== state.notificationHistory.length) {
                    state.notificationHistory = filteredHistory;
                    localStorage.setItem('notificationHistory', JSON.stringify(state.notificationHistory));
                    updateHistoryDisplay();
                }
            }
            
            // 清空所有历史记录函数
            async function clearAllHistory() {
                // 增强的确认对话框，更加明确操作后果
                if (confirm('确定要清空所有通知历史记录吗？\n此操作不可撤销。')) {
                    // 清空历史记录
                    state.notificationHistory = [];
                    localStorage.setItem('notificationHistory', JSON.stringify(state.notificationHistory));
                    updateHistoryDisplay();
                    
                    // 触觉反馈和提示
                    hapticFeedback.medium();
                    await showToast('通知历史记录已成功清空', 'success');
                }
            }
            
            // 初始化
            function init() {
                // 获取用户保存的主题或根据时间自动选择主题
                let savedTheme = localStorage.getItem('theme');
                
                // 如果没有保存的主题，根据当前时间自动选择白天或夜晚模式
                if (!savedTheme) {
                    const hour = new Date().getHours();
                    savedTheme = (hour >= 19 || hour < 7) ? 'dark' : 'light';
                }
                
                // 设置初始主题
                setTheme(savedTheme);
                
                // 设置初始紧急程度
                setUrgency('urgent');
                
                // 初始化时进行一次清理（防止累积太多历史记录）
                cleanupHistory();
                
                // 添加定时器，定期检查时间变化以自动切换主题（仅在无手动主题时）
                if (!localStorage.getItem('theme')) {
                    setInterval(() => {
                        const hour = new Date().getHours();
                        const currentTheme = document.body.className || 'light';
                        const expectedTheme = (hour >= 19 || hour < 7) ? 'dark' : 'light';
                        
                        // 如果当前主题与预期主题不符，则切换
                        if (currentTheme !== expectedTheme) {
                            setTheme(expectedTheme);
                        }
                    }, 60000); // 每分钟检查一次
                }
            }
            
            // 加载消息模板
            function loadMessageTemplates() {
                const templates = config.messageTemplates || [];
                elements.messageTemplate.innerHTML = '<option value="">请选择模板</option>';
                
                templates.forEach(template => {
                    const option = document.createElement('option');
                    option.value = template.text;
                    option.textContent = template.text;
                    elements.messageTemplate.appendChild(option);
                });
            }

            // 绑定事件监听器
            elements.themeToggleBtn.addEventListener('click', toggleTheme);
            elements.clearHistoryBtn.addEventListener('click', clearAllHistory);

            elements.urgencyBtns.forEach(btn => {
                btn.addEventListener('click', () => setUrgency(btn.dataset.urgency));
            });

            elements.messageTemplate.addEventListener('change', (e) => {
                if (e.target.value) {
                    elements.messageInput.value = e.target.value;
                }
            });

            // 更新历史记录显示
            updateHistoryDisplay();

            // 初始化加载消息模板
            loadMessageTemplates();



            elements.notifyBtn.addEventListener('click', notifyOwner);

            // 触摸事件
            elements.callSlider.addEventListener('touchstart', (e) => {
                state.isDragging = true;
                state.startX = e.touches[0].clientX;
                elements.callHandle.style.transition = 'none';
                elements.callProgress.style.transition = 'none';
                hapticFeedback.light();
            }, { passive: true });

            elements.callSlider.addEventListener('touchmove', (e) => {
                if (!state.isDragging) return;
                e.preventDefault();
                updateSlider(e.touches[0].clientX);
            }, { passive: false });

            // 鼠标事件
            elements.callSlider.addEventListener('mousedown', (e) => {
                state.isDragging = true;
                state.startX = e.clientX;
                elements.callHandle.style.transition = 'none';
                elements.callProgress.style.transition = 'none';
            });

            document.addEventListener('mousemove', (e) => {
                if (!state.isDragging) return;
                e.preventDefault();
                updateSlider(e.clientX);
            }, { passive: false });

            // 结束拖动事件
            ['mouseup', 'mouseleave', 'touchend', 'touchcancel'].forEach(event => {
                document.addEventListener(event, endDrag, { passive: true });
            });

            document.addEventListener('touchmove', (e) => {
                if (state.isDragging) e.preventDefault();
            }, { passive: false });

        // 启动应用
        init();
    }

    // 启动整个应用
    initApp();
})();